package com.lry.app;

import com.lry.app.service.impl.KvServiceImpl;
import com.lry.core.RaftNode;
import com.lry.core.RaftOptions;
import com.lry.core.Server;
import com.lry.server.RpcServer;
import com.lry.service.impl.RaftConsensusServiceImpl;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class ServerMain {


    public static void main(String[] args) throws IOException {

        //D:\\raft localhost:8081:1,localhost:8082:2,localhost:8083:3 localhost:8081:1
        Server server1 = new Server(1,"localhost",8081);
        Server server2 = new Server(2,"localhost",8082);
//        Server server3 = new Server(3,"localhost",8083);
        List<Server> servers = new ArrayList<>();
        servers.add(server1);
        servers.add(server2);
//        servers.add(server3);

        //启动所有节点
        for (Server server : servers) {
            CompletableFuture.runAsync(()->{
                RaftOptions raftOptions = new RaftOptions();
                raftOptions.setDataDir("d:\\raft\\"+server.getServerId());
                ExampleStateMachine stateMachine = new ExampleStateMachine(raftOptions.getDataDir());
                RaftNode raftNode = new RaftNode(raftOptions,server,servers,stateMachine);

                //注册raft节点间相互调用的服务
                RpcServer rpcServer = new RpcServer(server.getHost(),server.getPort());
                rpcServer.registerService(new RaftConsensusServiceImpl(raftNode));
                rpcServer.registerService(new KvServiceImpl(raftNode,stateMachine));

                rpcServer.start();
                raftNode.init();
            });
        }

        System.in.read();
    }
}
